package cn.itcast.util;

import cn.itcast.config.QuotConfig;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Date 2020/6/9
 */
public class HbaseUtil {

    private static final Logger log = LoggerFactory.getLogger(HbaseUtil.class);

    /*
      开发步骤：
      1.加载配置文件
      2.获取连接
      3.插入单列数据
      4.插入多列数据
      5.根据rowkey查询数据
      6.根据rowkey删除数据
   */
    static Connection connection = null;

    static {
        Configuration configuration = HBaseConfiguration.create();
        configuration.set("hbase.zookeeper.quorum", QuotConfig.config.getProperty("zookeeper.connect"));
        try {
            connection = ConnectionFactory.createConnection(configuration);
        } catch (IOException e) {
            log.error("hbase连接异常", e);
        }
    }

    /*
     *初始化表
     */
    public static Table getTable(String tableName) {
        Table table = null;
        try {
            table = connection.getTable(TableName.valueOf(tableName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return table;
    }

    //3.插入单列数据
    public static void putDataByRowkey(String tableName, String family, String colName, String colVal, String rowkey) {
        Table table = getTable(tableName);
        try {
            Put put = new Put(rowkey.getBytes());
            put.addColumn(family.getBytes(), colName.getBytes(), colVal.getBytes());
            table.put(put);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                table.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //4.插入多列数据
    public static void putMapDataByRowkey(String tableName, String family, Map<String, Object> map, String rowkey) {
        Table table = getTable(tableName);
        try {
            Put put = new Put(rowkey.getBytes());
            for (String key : map.keySet()) {
                put.addColumn(family.getBytes(), key.getBytes(), map.get(key).toString().getBytes());
            }
            table.put(put);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                table.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //5.根据rowkey查询数据
    public static String queryByRowkey(String tableName, String family, String colName, String rowkey) {
        Table table = getTable(tableName);
        String str = null;
        try {
            Get get = new Get(rowkey.getBytes());
            Result result = table.get(get);
            byte[] bytes = result.getValue(family.getBytes(), colName.getBytes());
            if (bytes != null) {
                str = new String(bytes);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                table.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return str;
    }

    /**
     * 6.根据rowkey删除数据
     */
    public static void delByRowkey(String tableName, String family, String rowkey) {

        Table table = getTable(tableName);
        try {
            Delete delete = new Delete(rowkey.getBytes());
            delete.addFamily(family.getBytes());
            table.delete(delete);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                table.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void put(String tableName, Put put){
        Table table = getTable(tableName);
        try {
            table.put(put);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                table.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 批量数据插入(项目中用)
     */
    public static void putList(String tableName, List<Put> puts) {
        Table table = getTable(tableName);
        try {
            table.put(puts);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                table.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static List<Map<String,Object>> scanQuery(String tableName, String family, String colTime, String colPrice,String colVol,String startKey, String endKey) {

        Table table = getTable(tableName);
        Scan scan = new Scan();
        scan.setStartRow(startKey.getBytes());//60000020211201093000
        scan.setStopRow(endKey.getBytes()); //60000020211201100000
        ResultScanner resultScanner = null;
        List<Map<String,Object>> list = new ArrayList<>();
        try {
            resultScanner = table.getScanner(scan);
            for (Result result : resultScanner) {
                String tradeTime = new String(result.getValue(family.getBytes(), colTime.getBytes()));
                String tradePrice = new String(result.getValue(family.getBytes(), colPrice.getBytes()));
                String tradeVolume = new String(result.getValue(family.getBytes(), colVol.getBytes()));
                HashMap<String, Object> map = new HashMap<>();
                map.put("tradeTime",tradeTime);
                map.put("tradePrice",tradePrice);
                map.put("tradeVolume",tradeVolume);
                list.add(map);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 区间查询
     */
    public static List<String> scanQuery2(String tableName,String family,String colName,String startKey,String endKey){

        List<String> list = new ArrayList<>();
        Table table = null;
        try {
            table = connection.getTable(TableName.valueOf(tableName));
            //区间查询
            Scan scan = new Scan();
            scan.setStartRow(startKey.getBytes());
            scan.setStopRow(endKey.getBytes());

            ResultScanner scanner = table.getScanner(scan);
            for (Result result : scanner) {
                //获取指定列下面的数据
                byte[] value = result.getValue(family.getBytes(), colName.getBytes());
                list.add(new String(value));
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                table.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return list;
    }
    public static void main(String[] args) {

//        //putDataByRowkey(String tableName, String family, String colName, String colVal, String rowkey) {
//        //插入单列
        putDataByRowkey("quot_stock","info","username","xiaoli","1002");
//        //插入多列
//        //putMapDataByRowkey(String tableName, String family, Map<String, Object> map, String rowkey) {
//        HashMap<String, Object> map = new HashMap<>();
//        map.put("username","xiaohua");
//        map.put("age",20);
//        map.put("address","beijing");
//        putMapDataByRowkey("test","info",map,"1002");
//        //根据rowkey查询数据
//        //queryByRowkey(String tableName, String family, String colName, String rowkey) {
//        String str = queryByRowkey("test", "info", "username", "1002");
//        System.out.println("<<<:"+str);

        // public static List<String> scanQuery2(String tableName,String family,String colName,String startKey,String endKey){
//        List<Map<String,Object>> list2 = new ArrayList<>();
//
//        List<String> list = scanQuery2("quot_stock", "info", "data",
//                "60028220211222105804", "60028320211222105759");
//
//
//        for (String str : list) {
//            JSONObject json = JSON.parseObject(str);
//            Long eventTime = json.getLong("eventTime");
//            //日期格式化
//
//            String closePrice = json.getString("closePrice");
//            String tradeAmtDay = json.getString("tradeAmtDay");
//            String tradeVolDay = json.getString("tradeVolDay");
//            Map<String, Object> map = new HashMap<>();
//            map.put("date",eventTime);
//            map.put("tradePrice",closePrice);
//            map.put("tradeVol",tradeVolDay);
//            map.put("tradeAmt",tradeAmtDay);
//            list2.add(map);
//        }
//        System.out.println("list:::"+list2);


        /**
         * 2.1.0
         */


    }


}
